package br.com.medical.shop.web.controladores.servico;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import br.com.medical.shop.negocio.administrativo.Usuario;
import br.com.medical.shop.negocio.sistema.Rom;

@Service
public class RomService {
	
	public final String URLBASEOPENMEETINGS = "http://www.labtime.ufg.br:5080/openmeetings";
//	public final String URLBASEOPENMEETINGS = "http://10.0.3.9:5080/openmeetings";
	
	public final String URLBASE = "http://www.labtime.ufg.br:8081/";
	private final String URLBASESISTEMA = "http://www.superinfo.no-ip.org/eproinfo/";
	private final String SISTEMA = "Eproinfo";
	private final String IDORG = "1";

	private String getValue(String url,String tagElemento) {
		try {
		 	SAXReader reader = new SAXReader();
		 	Document doc = reader.read(url);
		 	Element root = doc.getRootElement();
		 	for ( Object studentObj : root.elements()) {
		 	    Element studentElement = (Element) studentObj;
		 	    return studentElement.elementText(tagElemento) != null ? studentElement.elementText(tagElemento).toString() :
		 	    	studentElement.getStringValue();
		 	}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private String getIdSessionAdmin(){
		String username = "admin";
		String userpass = "admin";
		
		String session = getIdSession();
		getValue(URLBASEOPENMEETINGS+"/services/UserService/loginUser?SID="+session+"&username="+username+"&userpass="+userpass, null);
		return session;
	}
	
	private String getIdSession(){
		return getValue(URLBASEOPENMEETINGS+"/services/UserService/getSession","session_id");
	}
	
	private String getHash(Usuario usuario, HttpServletRequest request) {
		// TODO Auto-generated method stub
		loginUser(usuario);
		String session = getIdSessionAdmin();
		
		String id_room = request.getParameter("idRoom");
		int moderacao = 1;
		String urlImagem = URLBASESISTEMA+"/sistema/exibir_imagem.htm?propimg=true&codimgCodUsuario="+46+"&largimg=160&altimg=200&ctximg="+"Feminino";
		
		return getValue(URLBASEOPENMEETINGS+"/services/UserService/setUserObjectAndGenerateRoomHash?"
				+ "SID="+session
				+ "&username="+usuario.getCpf()
				+ "&firstname="+usuario.getApelido()
				+ "&lastname="+usuario.getNome()
				+ "&email="+usuario.getEmail()
				+ "&profilePictureUrl="+urlImagem
				+ "&externalUserId="+usuario.getId()
				+ "&externalUserType="+"eproinfo"
				+ "&room_id="+id_room
				+ "&becomeModeratorAsInt="+moderacao
				+ "&showAudioVideoTestAsInt=1",null);
	}
	
	private String loginUser(Usuario usuario){
		String session = getIdSession();
		
		int status = Integer.parseInt(getValue(URLBASEOPENMEETINGS+"/services/UserService/loginUser?"
				+ "SID="+session
				+ "&username="+usuario.getCpf()
				+ "&userpass="+usuario.getCpf()
				,null));

		if (status < 0) {
			return addUser(usuario);
		}else {
			return session;
		}
	}

	
	private String addUser(Usuario usuario){
		String session = getIdSessionAdmin();
		int idState = 29; //Brasil
		int language = 6; //Portugues
		int timeZone = 244; //America/Sao_Paulo 
		
		String idUser = getValue(URLBASEOPENMEETINGS+"/services/UserService/addNewUserWithExternalType?"
				+ "SID="+session
				+ "&username="+usuario.getCpf()
				+ "&userpass="+usuario.getCpf()
				+ "&firstname="+usuario.getApelido()
				+ "&lastname="+usuario.getNome()
				+ "&email="+usuario.getEmail()
				+ "&states_id="+idState
				+ "&language_id="+language
				+ "&jNameTimeZone="+timeZone
				+ "&externalUserId="+usuario.getId()
				+ "&externalUserType="+SISTEMA
				,null);
		
		String statusOrg = getValue(URLBASEOPENMEETINGS+"/services/UserService/addUserToOrganisation?"
				+ "SID="+session
				+ "&user_id="+idUser
				+ "&organisation_id=1"
				+ "&insertedby=6"
				,null);
		
		return session;
	}
	
	public String getRoomUrl(Usuario usuario, HttpServletRequest request){
		String hash = getHash(usuario,request);
		return URLBASEOPENMEETINGS+"?secureHash="+hash;
	}
	
	public List<Rom> getRooms(HttpServletRequest request){
		return getRooms(URLBASEOPENMEETINGS+"/services/RoomService/getRooms?"
				+ "SID="+getIdSessionAdmin()
				+ "&start=1"
				+ "&max=100"
				+ "&orderby=name"
				+ "&asc=true");
	}
	
	private List<Rom> getRooms(String url) {
		List<Rom> roms = new ArrayList<Rom>();
		try {
		 	SAXReader reader = new SAXReader();
		 	Document doc = reader.read(url);
		 	Element root = doc.getRootElement();
		 	for ( Object studentObj : root.elements()) {
		 	    for ( Object element : ((Element) studentObj).elements()){
		 	    	Element result = (Element) element;
		 	    	if (result.getName().equals("result")) {
		 	    		Rom rom = new Rom();
		 	    		rom.setId(Integer.parseInt(result.elementText("id")));
		 	    		rom.setName(result.elementText("name"));
		 	    		rom.setParticipantes(Integer.parseInt(result.elementText("numberOfPartizipants")));
		 	    		roms.add(rom);
					}
		 	    }
		 	}
		 	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return roms;
	}
	
	public String addRoom(HttpServletRequest request) {
		String url = URLBASEOPENMEETINGS+"/services/RoomService/addRoomWithModeration?"
				+ "SID="+getIdSessionAdmin()
				+ "&name="+request.getParameter("name")
				+ "&roomtypes_id=1"
				+ "&comment="+request.getParameter("descricao")
				+ "&numberOfPartizipants=40"
				+ "&ispublic="+request.getParameter("public")
				+ "&appointment=false"
				+ "&isDemoRoom=false"
				+ "&demoTime="
				+ "&isModeratedRoom=true";
		String idRoom =  getValue(url, null);
		addRoomToOrg(idRoom);
		return idRoom;
	}
	
	public void updateRoom(HttpServletRequest request) {
		String url = URLBASEOPENMEETINGS+"/services/RoomService/updateRoomWithModeration?"
				+ "SID="+getIdSessionAdmin()
				+ "&room_id="+request.getParameter("idRoom")
				+ "&name="+request.getParameter("name")
				+ "&roomtypes_id=1"
				+ "&comment="+request.getParameter("descricao")
				+ "&numberOfPartizipants=40"
				+ "&ispublic="+request.getParameter("public")
				+ "&appointment=false"
				+ "&isDemoRoom=false"
				+ "&demoTime="
				+ "&isModeratedRoom=true";
		getValue(url, null);
	}
	
	public void deleteRoom(HttpServletRequest request) {
		String url = URLBASEOPENMEETINGS+"/services/RoomService/deleteRoom?"
				+ "SID="+getIdSessionAdmin()
				+ "&room_id="+request.getParameter("idRoom");
		getValue(url, null);
	}
	
	private void addRoomToOrg(String idRoom){
		String url = URLBASEOPENMEETINGS+"/services/RoomService/addRoomToOrg?"
				+ "SID="+getIdSessionAdmin()
				+ "&room_id="+idRoom
				+ "&organisation_id="+IDORG;
		getValue(url, null);
	}
}
